<template>
	<view class="signature-container">
		<view class="preview-container" @tap="showSignatureBoard()">
			<image :src="signatureImgUrl" mode="scaleToFill"></image>
		</view>
		<view v-show="show" class="signature-board-container">
			<view class="signature-board-main" style="z-index: 3000;">
				<view class="signature-title"><text v-for="t in title">{{t}}</text></view>
				<canvas :id="cid+'master'" :canvas-id="cid" @touchmove='(e)=>move(e,1)' @touchstart='($event)=>{start($event,1)}' @touchend='(e)=>{end(e,1)}' @touchcancel='cancel' @longtap='tap' disable-scroll='true' @error='error'/>
				<view class="button-container">
					<view class="btn btn-cancel" @tap="cancelSignature()">
						<text>取</text><text>消</text>
					</view>
					<view class="btn btn-clear" @tap="clearSignature()">
						<text>清</text><text>空</text>
					</view>
					<view class="btn btn-submit" @tap="submitSignature()">
						<text>确</text><text>定</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
    /** 签名 */
    let content = null
    let touchs = []
    let canvasw = 0
    let canvash = 0
    //获取系统信息
    uni.getSystemInfo({
        success: function(res) {
            canvasw = res.windowWidth;
            canvash = res.windowHeight;
        },
    })
    export default {
        name:"HSignature",
        props: {
            value: {
                default: ''
            },
            cid: {
				type: String,
				default: 'signatureCanvas',
			},
            title: {
                type: String,
                default: '请签字',
            },
            disabled: {
                type: Boolean,
                default: false,
            }
        },
        cxt: null,
        data() {
            return {
                // 签名板显示隐藏
                show: false,
                // 是否签名
                isEnd: false,
                //
                previewSignatureImgUrl:'',

            };
        },
        watch: {
            value() {
                console.log('value',this.value)
                this.previewSignatureImgUrl = this.value;
            }
        },
        computed: {
            signatureImgUrl() {
                let pv = this.previewSignatureImgUrl
                console.log('signatureImgUrl',this.previewSignatureImgUrl)
                return pv
            }
        },
        methods: {
            showSignatureBoard(){
                let _ = this
				content = null
				if(_.disabled) return
                if (!content) {
                    _.initCanvas()
                } else if (!_.show) {
                    _.clearSignature()
                    _.show = true
                }
            },
            /** 按钮*/
            submitSignature() {
                let _ = this
                console.log('submitSignature')
                if (!this.isEnd) return uni.$u.toast('请完成签名！')
                console.log('请完成签名')
                uni.canvasToTempFilePath({
                    canvasId: _.cid,
                    success: function(res) {
                        // console.log('res.tempFilePath',res.tempFilePath,)
                        uni.uploadFile({
                            url: _.$C.upload,
                            filePath: res.tempFilePath,
                            name: 'file',
                            header: {
                                'Authorization': uni.getStorageSync('Authorization'),
                            },
                            formData: {},
                            success: async function(res) {
                                let ajaxData = JSON.parse(res.data)
                                if(ajaxData.code == 200) {
                                    _.$emit('input', ajaxData.data.filePath)
                                    _.$emit('getFileInfo', {fileId:ajaxData.data.fileId, filePath:ajaxData.data.filePath})
                                    _.previewSignatureImgUrl = ajaxData.data.filePath
                                    _.show = false
                                }else{
                                    uni.$u.toast(ajaxData.msg||'提交失败！')
                                }
                            }
                        })
                    }
                }, this)
            },
            cancelSignature() {
                let _ = this
                _.hideSignature()
            },
            hideSignature() {
                let _ = this
				content = null
                _.show = false
            },
            clearSignature() {
                let _ = this
                // 设置为未签名
                this.isEnd = false
                //清除画布
                content.clearRect(0, 0, canvasw, canvash)
                content.draw(true)
            },
            /** 签名 */
            initCanvas(){
                let _ = this
                content = uni.createCanvasContext(_.cid, this)
                content.setStrokeStyle("#000")
                content.setLineWidth(5)
                content.setLineCap('round')
                content.setLineJoin('round')
                console.log('initCanvas',content)
                _.show = true
            },
            // 画布的触摸移动开始手势响应
            start(event) {
                let point = {
                    x: event.changedTouches[0].x,
                    y: event.changedTouches[0].y
                }
                touchs.push(point);
            },
            // 画布的触摸移动手势响应
            move(e) {
                let point = {
                    x: e.touches[0].x,
                    y: e.touches[0].y
                }
                touchs.push(point)
                if (touchs.length >= 2) {
                    this.draw(touchs,1)
                }
            },

            // 画布的触摸移动结束手势响应
            end(e) {
                console.log("触摸结束" + e)
                // 设置为已经签名
                this.isEnd = true
                // 清空轨迹数组
                for (let i = 0; i < touchs.length; i++) {
                    touchs.pop()
                }
            },

            // 画布的触摸取消响应
            cancel(e) {
                console.log("触摸取消" + e)
            },

            // 画布的长按手势响应
            tap(e) {
                console.log("长按手势" + e)
            },

            error(e) {
                console.log("画布触摸错误" + e)
            },

            //绘制
            draw(touchs) {
                let point1 = touchs[0]
                let point2 = touchs[1]
                touchs.shift()
                content.moveTo(point1.x, point1.y)
                content.lineTo(point2.x, point2.y)
                content.stroke()
                content.draw(true)
            }
        },
    }
</script>
<style lang="scss" scope>
	@import 'index.scss';
</style>
